import { useEffect } from "react";
import { Popconfirm, Pagination, Avatar, message, Row, Col, Tag } from "antd";
import { Button, ButtonGroup, Card as SemiCard, List, Descriptions } from "@douyinfe/semi-ui";
import { IconPlusCircle, IconRefresh, IconDelete } from "@douyinfe/semi-icons";
import { useReactive } from "ahooks";
import { useModel } from "umi";
import Jdenticon from "react-jdenticon";
import { AllApplications, FindTaskInfo, DeleteTaskMember, AllTaskSceneMembers } from "../_graphql/tasks";
import SetSceneMembers from "../_modals/tasks/set.SceneMembers";

export default function TaskRolesPage() {
    const { windowInnerHeight, graphqlFetch } = useModel("global");
    const { kuboUrl } = useModel("kubo");
    const { setModalVisible, setModalTitle, setModalComponent, setModalStyle, setModalWidth } = useModel("global.modal");

    const state = useReactive({
        loading: false,
        taskLoading: false,
        applications: [],
        selectedApplication: {},

        taskRoles: [],
        orgTask: {}, //组织内查询出来的应用任务
        selectedTaskkey: null,
        selectedTaskInfo: null,

        memberLoading: false,
        taskMembers: [],
        taskGroupMembers: [],

        roleLoading: false,
        pageSize: 20,
        page: 1,
        totalCount: 0,
    });

    const loadApplications = async () => {
        state.loading = true;
        state.roles = [];
        let res = await graphqlFetch({
            query: AllApplications,
            variables: {
                first: state.pageSize || 20,
                offset: (state.page - 1) * state.pageSize || 0,
            },
        });
        state.applications = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.selectedApplication = res?.a?.totalCount ? res.a.nodes[0] : {};
        state.totalCount = res?.a?.totalCount;
        state.loading = false;
    };

    useEffect(() => {
        loadApplications();
    }, []);

    const loadApplicatinTasks = async () => {
        state.taskLoading = true;
        state.selectedTaskkey = null;
        state.selectedTaskInfo = null;
        state.taskRoles = [];
        try {
            const { aiUuid, aiName, b } = state.selectedApplication;
            let data = { aiUuid, aiName };
            if (b?.nodes?.length) data = { ...data, ...b.nodes[0] };
            if (data.atHash) {
                let response = await fetch(kuboUrl + data.atHash + "/task_roles.json", { cache: "no-cache" });
                let taskRoles = await response.json();
                let res = await graphqlFetch({
                    query: FindTaskInfo,
                    variables: {
                        aiUuid: state.selectedApplication.aiUuid,
                        atName: state.selectedTaskkey,
                    },
                });
                state.orgTask = res?.a?.nodes || [];
                if (state.orgTask.length > 0)
                    Object.keys(taskRoles).map((key) => {
                        if (state.orgTask.find((item) => item.atName === key).atVenu)
                            taskRoles[key].default = state.orgTask.find((item) => item.atName === key).atVenu;
                    });
                state.taskRoles = taskRoles;
                let keys = Object.keys(state.taskRoles);
                if (keys.length > 0) {
                    state.selectedTaskkey = keys[0];
                    state.selectedTaskInfo = { ...state.taskRoles[keys[0]], versions: state.taskRoles[keys[0]].versions[state.taskRoles[keys[0]].default] };
                }
            }
        } catch (error) {}
        state.taskLoading = false;
    };

    useEffect(() => {
        state.selectedApplication?.aiUuid && loadApplicatinTasks();
    }, [state.selectedApplication?.aiUuid]);

    const loadTaskMembers = async () => {
        state.memberLoading = true;
        let res = await graphqlFetch({
            query: AllTaskSceneMembers,
            variables: {
                atVenu: state.selectedTaskInfo.default,
                atName: state.selectedTaskkey,
                aiUuid: state.selectedApplication.aiUuid,
            },
        });
        state.taskMembers = res?.a?.nodes || [];
        state.taskGroupMembers = res?.a?.nodes ? helper.transGroup(res.a.nodes, "atRona", "atRona") : [];
        state.memberLoading = false;
    };

    useEffect(() => {
        state.selectedTaskInfo?.default && state.selectedApplication?.aiUuid && loadTaskMembers();
    }, [state.selectedTaskkey, state.selectedTaskInfo]);

    const openTasksSetMembers = () => {
        setModalTitle("设置任务角色成员");
        setModalStyle({ top: 100 });
        setModalWidth(700);
        setModalComponent(
            <SetSceneMembers
                application={state.selectedApplication}
                taskKey={state.selectedTaskkey}
                taskInfo={state.selectedTaskInfo}
                taskMembers={state.taskMembers}
                reloadData={loadTaskMembers}
            />
        );
        setModalVisible(true);
    };

    const deleteRoleMember = async (record) => {
        let res = await graphqlFetch({
            query: DeleteTaskMember,
            variables: {
                aiUuid: state.selectedApplication.aiUuid,
                atName: state.selectedTaskkey,
                omUuid: record.omUuid,
                atRona: record.atRona,
                atVenu: record.atVenu,
            },
        });
        if (res) {
            message.success("成功移除应用角色成员信息");
            loadTaskMembers();
        }
    };

    // 窗口头部：30，应用头：60，操作区内边距：24，卡面头：53，卡面脚：56，修正值：4
    const cardBodyHeight = windowInnerHeight - 90 - 48 - 53 - 12;

    return (
        <Row style={{ margin: 24 }} gutter={16}>
            <Col span={6}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>应用列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplications()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight - 56 }}
                    footerStyle={{ padding: 0 }}
                    footerLine={true}
                    footer={
                        <div style={{ padding: 14, display: "flex", justifyContent: "space-between" }}>
                            <div></div>
                            <Pagination
                                total={state.totalCount}
                                showTotal={(total, range) => `当前显示第 ${range[0]}-${range[1]} 条，共 ${total} 条`}
                                pageSize={state.pageSize}
                                current={state.page}
                                showSizeChanger={false}
                                onChange={(page) => (state.page = page)}
                            />
                        </div>
                    }
                >
                    <List
                        loading={state.loading}
                        dataSource={state.applications}
                        style={{ padding: 10, height: cardBodyHeight - 56, overflow: "auto" }}
                        renderItem={(item, index) => (
                            <List.Item
                                key={index}
                                className={`list-item ${state.selectedApplication?.aiUuid === item?.aiUuid ? "list-item-selected" : ""}`}
                                header={<Avatar shape="square" src={<Jdenticon value={item.aiName || "-"} />} />}
                                main={
                                    <div>
                                        <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.aiName || "-"}</div>
                                        {item?.aiDesc}
                                    </div>
                                }
                                onClick={() => (state.selectedApplication = item)}
                            ></List.Item>
                        )}
                    />
                </SemiCard>
            </Col>
            <Col span={5}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>任务列表</span>}
                    headerExtraContent={<Button theme="borderless" icon={<IconRefresh />} onClick={() => loadApplicatinTasks()} />}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                >
                    <List
                        loading={state.roleLoading}
                        dataSource={Object.keys(state.taskRoles)}
                        renderItem={(key, index) => {
                            const item = state.taskRoles[key];
                            return (
                                <List.Item
                                    key={index}
                                    className={`list-item ${state.selectedTaskkey === key ? "list-item-selected" : ""}`}
                                    header={<Avatar shape="square" src={<Jdenticon value={item.content || "-"} />} />}
                                    main={
                                        <div>
                                            <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.content + " " || " - "}</div>
                                            {<Tag color="blue">{item?.type}</Tag>}
                                        </div>
                                    }
                                    onClick={() => (
                                        (state.selectedTaskkey = key),
                                        (state.selectedTaskInfo = {
                                            ...state.taskRoles[key],
                                            versions: state.taskRoles[key].versions[state.taskRoles[key].default],
                                        })
                                    )}
                                ></List.Item>
                            );
                        }}
                    />
                </SemiCard>
            </Col>

            <Col span={6}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>任务版本</span>}
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight, overflow: "auto" }}
                >
                    {state.selectedTaskInfo?.type === "任务" && (
                        <SemiCard
                            title={<span style={{ lineHeight: "32px", fontWeight: 600 }}>{state.selectedTaskInfo?.default}</span>}
                            style={{ margin: 10 }}
                            bordered
                            headerStyle={{ padding: "5px 14px" }}
                        >
                            <Descriptions align="left" style={{ width: "100%", marginLeft: 10 }}>
                                {Object.values(state.selectedTaskInfo?.versions).map((_item, index) => (
                                    <Descriptions.Item key={index} itemKey={_item.label}>
                                        <div style={{ marginLeft: 50 }}>{_item.text}</div>
                                    </Descriptions.Item>
                                ))}
                            </Descriptions>
                        </SemiCard>
                    )}
                </SemiCard>
            </Col>

            <Col span={7}>
                <SemiCard
                    title={<span style={{ lineHeight: "32px", fontSize: 16, fontWeight: 600 }}>{"成员列表"}</span>}
                    headerExtraContent={
                        <ButtonGroup size={"default"} theme="borderless">
                            <Button icon={<IconPlusCircle />} disabled={!state.selectedTaskkey} onClick={openTasksSetMembers}></Button>
                            <Button icon={<IconRefresh />} onClick={loadTaskMembers}></Button>
                        </ButtonGroup>
                    }
                    headerStyle={{ padding: "10px 14px" }}
                    shadows="always"
                    bordered={false}
                    bodyStyle={{ padding: 0, height: cardBodyHeight }}
                >
                    {state.selectedTaskInfo?.type === "任务" && (
                        <>
                            {state.taskGroupMembers.map((item) => (
                                <List
                                    key={item.atRona}
                                    header={item.atRona}
                                    loading={state.memberLoading}
                                    dataSource={item.items}
                                    renderItem={(item, index) => {
                                        return (
                                            <List.Item
                                                key={index}
                                                className={`list-item`}
                                                header={<Avatar shape="square" src={<Jdenticon value={item?.member?.omName || "-"} />} />}
                                                main={
                                                    <div>
                                                        <div style={{ color: "var(--semi-color-text-0)", fontWeight: 500 }}>{item?.member?.omName || "-"}</div>
                                                        {item?.member.omRoge} - {item?.member.omIfim ? "内部成员" : "外部成员"} - {item?.member.omPosi}
                                                    </div>
                                                }
                                                extra={
                                                    <Popconfirm
                                                        placement="topRight"
                                                        title={`确认要从任务角色里移除该成员【${item?.member?.omName}】吗?`}
                                                        onConfirm={() => deleteRoleMember(item)}
                                                    >
                                                        <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />} />
                                                    </Popconfirm>
                                                }
                                            ></List.Item>
                                        );
                                    }}
                                />
                            ))}
                        </>
                    )}
                </SemiCard>
            </Col>
        </Row>
    );
}
